package com.geeguo.ebuilder.client.business.system.userrole.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.geeguo.ebuilder.client.base.database.annotation.TDS;
import com.geeguo.ebuilder.client.base.tenant.model.DataContext;
import com.geeguo.ebuilder.client.business.system.userrole.mapper.UserRoleMapper;
import com.geeguo.ebuilder.client.business.system.userrole.model.UserRoleEntity;
import com.geeguo.ebuilder.client.business.system.userrole.service.UserRoleService;
import com.geeguo.ebuilder.core.common.utils.key.UUIDGenerator;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Service
public class UserRoleServiceImpl extends ServiceImpl<UserRoleMapper, UserRoleEntity> implements UserRoleService {

    @Autowired
    private UserRoleMapper userRoleMapper;

    @TDS
    @Override
    @Transactional
    public boolean batchSave(List<UserRoleEntity> list, DataContext dataContext) {
        return this.saveBatch(list);
    }

    @TDS
    @Override
    @Transactional
    public boolean batchSave(List<String> roleIds, String userId, String createUserId, DataContext dataContext) {
        userRoleMapper.deleteByUser(userId);
        if (CollectionUtils.isNotEmpty(roleIds)) {
            List<UserRoleEntity> entityList = new ArrayList<>();
            for (String roleId : roleIds) {
                UserRoleEntity entity = new UserRoleEntity();
                entity.setId(UUIDGenerator.getId());
                entity.setUserId(userId);
                entity.setRoleId(roleId);
                entity.setTenantCode(dataContext.getTenantCode());
                entity.setCreateTime(new Date());
                entity.setCreateUser(createUserId);
                entityList.add(entity);
            }
            return this.saveBatch(entityList);
        }
        return true;
    }

    @TDS
    @Override
    public boolean removeByUserId(String userId, DataContext dataContext) {
        return userRoleMapper.deleteByUser(userId) >= 0;
    }
}